﻿var dayName = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
        'September', 'October', 'November', 'December'];
var selectedDate;

function Event(ev) {
    this.EventID = ev.EventID;
    this.Type = ev.Type;
    this.StartDate = ev.StartDate;
    this.EndDate = ev.EndDate;
    this.Desc = ev.Desc;
    this.Location = ev.Location;
    this.EventType = ev.EventTypeID;
}

$(document).ready(function () {
    $("#datepicker").datepicker({
        autoSize: true,
        onSelect: dateSelect
    });
    $("#calendar").draggable();
    //$( "#datepicker" ).datepicker( "option", "changeYear", true );
    $("#datepicker").datepicker("option", "yearRange", ((new Date).getFullYear() + ':' + ((new Date).getFullYear() + 4)));
    $("#datepicker").datepicker("option", "dateFormat", 'D, dd M yy');
    $("#changeYear").click(ChangeYear);
    $("#datePart").click(ShowDatepicker);
    $("#showEventButton").toggle(ShowEventList, HideEventList);
    $("#newEventButton").click(NewEvent);
    $("#save2").click(SaveEvent);
    PopulateStartTimeOption();
    $("#inputEventStartTime").change(function () {
        var s = $("#inputEventStartTime").val();

        PopulateEndTimeOption(s);
    })

    ///-----------------


});


//This function will be called when the Change Year Button is Clicked.
function ChangeYear() {
    var changeYear = $("#datepicker").datepicker("option", "changeYear");
    if (!changeYear) {
        $("#changeYear").text("Cancel");
        $("#datepicker").datepicker("option", "changeYear", true);
    }
    else {
        $("#changeYear").text("Change Year");
        $("#datepicker").datepicker("option", "changeYear", false);
    }
}

//This function will be called when you click on a date in the datePicker
function dateSelect(dateText, inst) {

    $("#datepicker").hide();
    $("#oneDayView").slideDown(1000);
    var date = new Date(dateText);
    var today = new Date();
    selectedDate = date;
    $("#dayName").text(dayName[date.getDay()]);
    $("#dateOfMounth").text(date.getDate());
    $("#year").text(date.getFullYear());
    $("#month").text(monthName[date.getMonth()]);
    if (date.toDateString() == today.toDateString()) {
        itIsToday();
    }
    else {
        itIsNotToday();
    }

}

//This function will be called when you click on the one Day view 
function ShowDatepicker() {
    HideEventList();
    $("#oneDayView").hide();
    $("#datepicker").slideDown(1000);
    $(".Calendar").css("background-color", "#afafaf");
}


//This function will show the event list 
function ShowEventList() {
    $("#showEventText").text("Hide Event List");
    $("#eventList").slideDown(1000);
    $("#showEventImage").attr("src", "../TemplateImages/eventSlideUp.png");
    GetEventList();
}

//This function will hide the event list
function HideEventList() {
    $("#showEventText").text("Show Event List");
    $("#eventList").slideUp(1000);
    $("#showEventImage").attr("src", "../TemplateImages/eventSlideDown.png");
    $("#eventContainer li").remove();

}

//This function checks whether it is today or not
function itIsToday() {
    $(".Calendar").css("background-color", "#FF8409");
    $(".OneDayView").css("background-color", "#FF8409");
    $("#showEventImage").attr("src", "../TemplateImages/eventSlideDown.png");

}

function itIsNotToday() {
    $(".Calendar").css("background-color", "#afafaf");
    $(".OneDayView").css("background-color", "#afafaf");
    $("#showEventImage").attr("src", "../TemplateImages/eventSlideDown.png");
}

function NewEvent() {
    $("#inputEventName").val("");
    $("#inputEventDesc").val("");
    $("#inputEventLocation").val("");
    $("#inputEventStartDate").val("");
    $("#inputEventEndDate").val("");
    $("#inputEventStartTime").val(0);
    $("#inputEventEndTime").val(0);
    $("#eventDesc ul").hide();
    $(".Dialog").fadeIn(4000);
    $('#inputEventStartDate').datepicker({
        minDate: '0',
        onSelect:
        function (dateText, inst) {
            $('#inputEventEndDate').datepicker("option", 'minDate', new Date(dateText));
            $('#inputEventEndDate').removeAttr("disabled");
        }
      ,
        onClose: function () { $(this).focus(); }
    });

    $("#inputEventEndDate").datepicker();
    $("#newEvent").dialog({ buttons: [{ text: "Save", click: function () { SaveEvent(); } },
             { text: "Cancel", click: function () { $(this).dialog("close"); } }],
        position: ['center', 'center'],
        modal: true,
        bgiframe: true,
        width: 300
    });
    $("#eventDesc ul").show();
    $("#newEvent").dialog();
}



//save an event
function SaveEvent() {

    var Type = $("#inputEventName").val();
    var Desc = $("#inputEventDesc").val();
    var Location = $("#inputEventLocation").val();
    var StartDate = $("#inputEventStartDate").val();
    StartDate = new Date(StartDate);
    var temp = $("#inputEventStartTime").toArray();
    temp = temp[0];
    temp = temp[$("#inputEventStartTime").val()]
    temp = $(temp).text();
    temp2 = temp.split(":");
    StartDate.setHours(temp2[0]);
    StartDate.setMinutes(temp2[1]);
    $('#inputEventEndDate').attr("disabled", "disabled");

    var EndDate = $("#inputEventEndDate").val();
    EndDate = new Date(EndDate);
    var temp = $("#inputEventEndTime").toArray();
    temp = temp[0];
    temp = temp[$("#inputEventEndTime").val()]
    temp = $(temp).text();
    temp2 = temp.split(":");
    EndDate.setHours(temp2[0]);
    EndDate.setMinutes(temp2[1]);
    var EventType = $("#eventType").val();
    var Json_var = {
        Type: Type,
        Desc: Desc,
        Location: Location,
        StartDate: StartDate,
        EndDate: EndDate,
        EventTypeID: EventType
    };
    Json_var = JSON.stringify(Json_var);
    $.post("AjaxController.ashx", {

        ACTION: "NEWEVENT",
        ACTIONTYPE: "CALENDAR",
        DATA: Json_var
    }, function (result) {

        if (result == 1) {
            RefreshEventList();
            alert("New Event created");
            $("#newEvent").dialog("close");

        }
        else if (result == 0) {
            alert("Failed");
            $("#newEvent").dialog("close");
        }

    });
}
//Delete event by eventId
function DeleteEvent(eventId) {
    var conf = confirm("Do you want to delete this event? ");
    if (conf == true) {
        $("#eventID" + eventId).btOff();
        $.post("AjaxController.ashx", {

            ACTION: "DELETEEVENT",
            ACTIONTYPE: "CALENDAR",
            DATA: eventId
        }, function (result) {

            if (result == 1) {
                RefreshEventList();
                alert("Event Deleted");


            }
            else {
                alert("Failed");
                $("#eventID" + eventId).btOff();
            }

        });
    }
}

function EditEvents(eventID) {
    var events;
    $.post("AjaxController.ashx", {
        ACTION: "EVENTBYID",
        ACTIONTYPE: "CALENDAR",
        DATA: eventID
    }, function (result) {
        events = JSON.parse(result);
        eve = new Event(events[0]);
        GetEventEdition(eve.EventID, eve.Type, eve.Desc, eve.Location, eve.StartDate, eve.EndDate);
    });

}


//Edit an event by event attributes
function GetEventEdition(Event_ID, Event_Type, Event_Desc, Event_Location, Event_StartDate, Event_EndDate) {
    var Type = $("#inputEventName").val(Event_Type);
    var Desc = $("#inputEventDesc").val(Event_Desc);
    var Location = $("#inputEventLocation").val(Event_Location);
    date = (parseInt(Event_StartDate.substr(6)));
    tempDate = new Date(date);
    $("#inputEventStartDate").val(tempDate.toDateString());
    $("#inputEventStartTime").val(tempDate.getHours() + ":" + tempDate.getMinutes());
    date = (parseInt(Event_EndDate.substr(6)));
    tempDate = new Date(date);
    $("#inputEventEndDate").val(tempDate.toDateString());
    $("#inputEventEndTime").val(tempDate.getHours() + ":" + tempDate.getMinutes());
    $('#inputEventEndDate').removeAttr("disabled");
    $("#inputEventId").val(Event_ID)
    $("#newEvent").dialog({ buttons: [{ text: "Edit", click: function () { EditEvent(); } },
             { text: "Cancel", click: function () { $(this).dialog("close"); $('#inputEventEndDate').attr("disabled", "disabled"); } }],
        position: ['center', 'center'],
        modal: true,
        bgiframe: true,
        width: 300
    });

}

function EditEvent() {
    var Id = $("#inputEventId").val();
    var Type = $("#inputEventName").val();
    var Desc = $("#inputEventDesc").val();
    var Location = $("#inputEventLocation").val();
    var StartDate = $("#inputEventStartDate").val();
    StartDate = new Date(StartDate);
    var temp = $("#inputEventStartTime").toArray();
    temp = temp[0];
    temp = temp[$("#inputEventStartTime").val()]
    temp = $(temp).text();
    temp2 = temp.split(":");
    StartDate.setHours(temp2[0]);
    StartDate.setMinutes(temp2[1]);
    $('#inputEventEndDate').attr("disabled", "disabled");

    var EndDate = $("#inputEventEndDate").val();
    EndDate = new Date(EndDate);
    var temp = $("#inputEventEndTime").toArray();
    temp = temp[0];
    temp = temp[$("#inputEventEndTime").val()]
    temp = $(temp).text();
    temp2 = temp.split(":");
    EndDate.setHours(temp2[0]);
    EndDate.setMinutes(temp2[1]);
    var EventType = $("#eventType").val();
    var Json_var = {
        EventID: Id,
        Type: Type,
        Desc: Desc,
        Location: Location,
        StartDate: StartDate,
        EndDate: EndDate,
        EventTypeID: EventType
    };
    Json_var = JSON.stringify(Json_var);
    $.post("AjaxController.ashx", {

        ACTION: "EDITEVENT",
        ACTIONTYPE: "CALENDAR",
        DATA: Json_var
    }, function (result) {

        if (result == 1) {
            RefreshEventList();
            alert("Event Edited");
            $("#newEvent").dialog("close");

        }
        else if (result == 0) {
            alert("Failed");
            $("#newEvent").dialog("close");
        }

    });
}

function GetEventList() {
    test = selectedDate
    var day = test.getDate();
    var mounth = test.getMonth() + 1;
    var year = test.getFullYear();
    var events;
    $("#ajaxLoader").show();
    $.post("AjaxController.ashx", {
        ACTION: "EVENTLIST",
        ACTIONTYPE: "CALENDAR",
        DAY: day,
        MOUNTH: mounth,
        YEAR: year
    }, function (result) {
        events = JSON.parse(result);
        $("#ajaxLoader").hide();
        CreateEventList(events)
    });
}

function CreateEventList(events) {
    var eventLists = [10];
    for (i = 0; i < events.length; i++) {
        eventLists[i] = new Event(events[i]);
        var eventText = '<li class="eventElement" id="eventID' +
                     eventLists[i].EventID
                     + '">'
                    + '<img src="../TemplateImages/EventTypeIcon/'
                    + eventLists[i].EventType +
                    '.png" /><a href="#"><img alt="Edit" src="../TemplateImages/pencil.ico" class="DeleteEditIcon EditEvent" key="' + eventLists[i].EventID + '"/></a><a href="#"><img alt="Delete"'
                    + ' src="../TemplateImages/gnome_edit_delete.ico" class="DeleteEditIcon DeleteEvent"  key="' + eventLists[i].EventID + '" /></a>' +
                    eventLists[i].Type + '</li>';
        $("#eventContainer").append(eventText);
        var el = "#eventID" + eventLists[i].EventID
        EventDetail(el, eventLists[i]);
        $(".DeleteEvent").click(
                function () {
                    DeleteEvent($(this).attr("key"));
                }

                );
        $(".EditEvent").click(

                       function () {
                           EditEvents($(this).attr("key"));
                       }

                )
    }
}

function EventDetail(element, eve) {
    var SDate = $("#dialogStartDate");
    var STime = $("#dialogStartTime");
    var EDate = $("#dialogEndDate");
    var ETime = $("#dialogEndTime");
    var Loc = $("#dialogLocation");
    var desc = $("#dialogDescription");
    var tempDate;
    if (eve.StartDate != null) {
        date = (parseInt(eve.StartDate.substr(6)));
        tempDate = new Date(date);

        $(SDate).html(tempDate.toDateString());
        $(STime).text(tempDate.getHours() + ":" + tempDate.getMinutes());
    }
    if (eve.EndDate != null) {
        date = (parseInt(eve.EndDate.substr(6)));
        tempDate = new Date(date);
        $("#dialogEndDate").html(tempDate.toDateString());

        $(ETime).text(tempDate.getHours() + ":" + tempDate.getMinutes());
    }
    $(Loc).html(eve.Location);
    $(desc).html(eve.Desc);
    $(element).attr("title", $("#eventDesc").html())
    $(element).bt({
        padding: 20,
        width: 200,
        spikeLength: 40,
        spikeGirth: 40,
        cornerRadius: 40,
        fill: 'rgba(0, 0, 0, .8)',
        strokeWidth: 3,
        strokeStyle: '#CC0',
        cssStyles: { color: '#FFF', fontWeight: 'bold' }
    });
}

function PopulateStartTimeOption() {

    for (i = 0; i < 48; i = i + 2) {
        var time1 = i / 2 + ":" + "00";
        var time2 = i / 2 + ":" + "30";
        option = '<option value="' + i + '">' + time1 + '</option>';
        option = option + '<option value="' + (i + 1) + '">' + time2 + '</option>';
        $("#inputEventStartTime").append(option);
    }
    PopulateEndTimeOption(0);

}

function PopulateEndTimeOption(start) {

    $("#inputEventEndTime option").remove();
    var a = $("#inputEventStartTime").toArray();
    option = a[0];
    for (i = start; i < 48; i++) {
        opt = '<option value="' + i + '">' + $(option[i]).text() + '</option>';
        $("#inputEventEndTime").append(opt);
    }

}

function RefreshEventList() {
    $("#eventContainer li").remove();
    GetEventList();
}

   